from PyQt5.QtWidgets import QTableWidget, QTableWidgetItem, QHeaderView
from PyQt5.QtGui import QColor, QBrush

class AccountTableWidget(QTableWidget):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.setColumnCount(3)
        self.setHorizontalHeaderLabels(["邮箱", "密码", "状态"])
        self.horizontalHeader().setSectionResizeMode(0, QHeaderView.Stretch)
        self.horizontalHeader().setSectionResizeMode(1, QHeaderView.Stretch)
        self.horizontalHeader().setSectionResizeMode(2, QHeaderView.ResizeToContents)
        
    def load_accounts(self, accounts):
        self.setRowCount(0)
        for account in accounts:
            row = self.rowCount()
            self.insertRow(row)
            self.setItem(row, 0, QTableWidgetItem(account.get('email', '')))
            self.setItem(row, 1, QTableWidgetItem(account.get('password', '')))
            
            status_item = QTableWidgetItem("")
            if account.get("registered"):
                status_text = "已注册"
                status_item.setText(status_text)
                status_item.setToolTip(f"已注册Cursor账号，Token: {account.get('token', '')[:10]}...")
                status_item.setBackground(QBrush(QColor(200, 255, 200)))
            self.setItem(row, 2, status_item)
    
    def get_accounts(self):
        accounts = []
        for row in range(self.rowCount()):
            email = self.item(row, 0).text().strip() if self.item(row, 0) else ""
            password = self.item(row, 1).text().strip() if self.item(row, 1) else ""
            status_item = self.item(row, 2)
            registered = status_item and status_item.text() == "已注册"
            
            if email and password:
                account = {"email": email, "password": password}
                if registered:
                    account["registered"] = True
                accounts.append(account)
        return accounts
    
    def add_empty_row(self):
        row = self.rowCount()
        self.insertRow(row)
        self.setItem(row, 0, QTableWidgetItem(""))
        self.setItem(row, 1, QTableWidgetItem(""))
        self.setItem(row, 2, QTableWidgetItem(""))
        
    def remove_selected_rows(self):
        rows = set()
        for item in self.selectedItems():
            rows.add(item.row())
        
        for row in sorted(rows, reverse=True):
            self.removeRow(row) 